import os
from .base import Tool

def execute(params: dict) -> str:
    """执行list_files工具"""
    try:
        path = params.get("path", "")
        if not path:
            return "错误：未提供路径"
            
        if not os.path.exists(path):
            return f"错误：路径不存在 {path}"
            
        if not os.path.isdir(path):
            return f"错误：不是目录 {path}"
            
        # 获取目录内容
        items = os.listdir(path)
        
        # 分类文件和文件夹
        folders = []
        files = []
        
        for item in items:
            full_path = os.path.join(path, item)
            if os.path.isdir(full_path):
                folders.append(item)
            else:
                files.append(item)
                
        # 构建结果字符串
        result = f"目录 {path} 的内容:\n\n"
        
        if folders:
            result += "文件夹:\n"
            for folder in sorted(folders):
                result += f"📁 {folder}\n"
            result += "\n"
            
        if files:
            result += "文件:\n"
            for file in sorted(files):
                result += f"📄 {file}\n"
                
        if not items:
            result += "（目录为空）"
            
        return result
        
    except Exception as e:
        return f"列出文件失败: {str(e)}"

TOOL = Tool(
    name="list_files",
    description="列出指定目录下的所有文件和文件夹",
    parameters={
        "path": {
            "type": "string",
            "description": "要列出内容的目录路径",
            "required": True
        }
    },
    example='''<list_files>
<path>C:\\Users\\用户名\\Documents</path>
</list_files>''',
    execute_func=execute
)

def format_size(size_in_bytes: int) -> str:
    """格式化文件大小"""
    for unit in ['B', 'KB', 'MB', 'GB', 'TB']:
        if size_in_bytes < 1024.0:
            return f"{size_in_bytes:.1f} {unit}"
        size_in_bytes /= 1024.0
    return f"{size_in_bytes:.1f} TB"

def format_time(timestamp: float) -> str:
    """格式化时间戳"""
    return datetime.fromtimestamp(timestamp).strftime('%Y-%m-%d %H:%M:%S')

def list_directory(path: str) -> tuple[list, str]:
    """列出目录内容"""
    try:
        # 确保路径存在
        path = os.path.expanduser(path)
        path = os.path.expandvars(path)
        if not os.path.exists(path):
            return None, f"路径不存在: {path}"
        
        # 获取目录内容
        items = os.listdir(path)
        result = []
        
        for item in items:
            item_path = os.path.join(path, item)
            try:
                stats = os.stat(item_path)
                item_info = {
                    "name": item,
                    "type": "目录" if os.path.isdir(item_path) else "文件",
                    "size": format_size(stats.st_size) if os.path.isfile(item_path) else "-",
                    "modified": format_time(stats.st_mtime)
                }
                result.append(item_info)
            except:
                continue
        
        # 排序：目录在前，文件在后，按名称排序
        result.sort(key=lambda x: (x["type"] != "目录", x["name"].lower()))
        
        return result, None
        
    except Exception as e:
        return None, f"列出目录内容时出错: {str(e)}"